package com.jiaoyou.controller;

import com.jiaoyou.pojo.User;
import com.jiaoyou.service.UserService;
import com.jiaoyou.vo.ErrorResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    public ResponseEntity<Object> login(@RequestBody Map<String, String> param) {
        String mobile = param.get("phone");
        String code = param.get("verificationCode");
        String token = this.userService.login(mobile, code);

        //判断token
        if (StringUtils.isNotEmpty(token)) {
            //登陆成功
            String[] split = StringUtils.split(token, '|');//进行字符分割
            Boolean isNew = Boolean.valueOf(split[0]);
            String tokenStr = split[1];

            Map<String, Object> result = new HashMap<>();
            result.put("isNew", isNew);
            result.put("token", tokenStr);
            return ResponseEntity.ok(result);
        }
            ErrorResult.ErrorResultBuilder resultBuilder =
            ErrorResult.builder().errCode("000000").errMessage("发送短信验证码失败");

            return
            ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(resultBuilder.build());
    }
    /**
     * 根据token查询用户数据
     *
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.queryUserByToken(token);
    }

}
